const HttpException = require('../exception/http');

module.exports = (options, app) => {
	return async function tokenHandler(ctx, next) {
		// 获取白名单
		// const { whiteList } = options;
		const { app, request } = ctx;
		const whiteList = app.config.whiteList;
        const url = request.url;
        // Basic-eyxxxxx
		const authorization = request.header.authorization;
		let token = null;
		if (authorization) {
			token = authorization.substring(6);
		}
		const isWhite = whiteList.some((white) => {
			const index = white.indexOf('*');
			const path = white.substring(0, index > -1 ? index : white.length);
			return url.indexOf(path) > -1;
		});
		// 如果不是白名单,并且token不存在
		if (!isWhite && !token) throw new HttpException(403, 'token不存在');
		// token 存在
		if (!isWhite && token) {
			// 解析token
			try {
				// 解码token
				user = await ctx.app.jwt.verify(token, app.config.jwt.secret); //验证token
				// console.log('user======>', user);
				// 获取用户信息
				ctx.state.user = user;
            } catch (error) {
                // console.log("error======", error);
				throw new HttpException(403, 'token不合法');
			}
			//切记先解析token并存储数据后再执行回调，否则解析数据获取不到x
		}

		// console.log(app.config, 'config===========');
		// const { controller, router,  } = app;
		await next();
	};
};
